<?php

	include_once '../com/mss/model/Monastery.php';
	include '../com/mss/common/Connection.php';
	
	class MonasteryAccessor {
		
		public function saveAll(array $monasteries) {
			foreach ($monasteries as $monastery) {
				$this->save($monastery);
			}
		}
		
		public function save(Monastery $monastery) {
			$connection = Connection::open();
			$name = $monastery->getName();
			$location = $monastery->getLocation();
			$telephone = $monastery->getTelephone();
			$address = $monastery->getAddress();
			
			$query = "INSERT INTO SS_MONESTARY (NAME, LOCATION, TELEPHONE, ADDRESS) 
			VALUES ('$name', '$location', '$telephone', '$address')";
			
			mysql_query($query, $connection) or die("error occured whilie inserting data");
			Connection::close($connection);
		}
		
		public function selectAll() {
			$connection = Connection::open();
			
			$query = "SELECT * FROM SS_MONESTARY";
			$result = mysql_query($query, $connection) or die("error occured whilie inserting data");
			
			$monasteries = array();
			while ($row = mysql_fetch_assoc($result)) {
				$id = $row['ID'];
				$name = $row['NAME'];
				$location = $row['LOCATION'];
				$telephone = $row['TELEPHONE'];
				$address = $row['ADDRESS'];
				
				$monestary = new Monastery($id, $name, $location, $address, $telephone);
				array_push($monasteries, $monestary);
			}
			Connection::close($connection);
			
			return $monasteries;
		}
		
		public function select($id) {
			$connection = Connection::open();
			
			$query = "SELECT * FROM SS_MONESTARY WHERE ID = '$id'";
			
			$result = mysql_query($query, $connection) or die("error occured whilie selecting data");
			
			$row = mysql_fetch_assoc($result);
			$id = $row['ID'];
			$name = $row['NAME'];
			$location = $row['LOCATION'];
			$telephone = $row['TELEPHONE'];
			$address = $row['ADDRESS'];
				
			$monastery = new Monastery($id, $name, $location, $address, $telephone);

			Connection::close($connection);
			
			return $monastery;			
		}
		
		public function update(Monastery $monastery) {
			$connection = Connection::open();
			$id = $monastery->getID();
			$name = $monastery->getName();
			$location = $monastery->getLocation();
			$telephone = $monastery->getTelephone();
			$address = $monastery->getAddress();
			
			$query = "UPDATE SS_MONESTARY SET NAME = '$name',
			 LOCATION = '$location', ADDRESS = '$address',
			  TELEPHONE = '$telephone' WHERE ID = '$id'";

			mysql_query($query, $connection) or die("error occured whilie updating data");
			Connection::close($connection);			
		}
	}

?>